package top.techqi.core

import android.annotation.SuppressLint
import android.app.Application
import androidx.core.content.pm.PackageInfoCompat

@SuppressLint("PrivateApi")
@Suppress("unused")
object App {
    val INSTANCE: Application by lazy {
        try {
            return@lazy Class.forName("android.app.AppGlobals")
                .getMethod("getInitialApplication")
                .invoke(null) as Application
        } catch (_: Throwable) {
        }
        try {
            return@lazy Class.forName("android.app.ActivityThread")
                .getMethod("currentApplication")
                .invoke(null) as Application
        } catch (_: Throwable) {
        }
        throw KotlinReflectionNotSupportedError("No Application found.")
    }

    var packageName: String = ""
        private set
        get() {
            if (field.isEmpty()) fillVersionFields()
            return field
        }

    var versionName: String = ""
        private set
        get() {
            if (field.isEmpty()) fillVersionFields()
            return field
        }

    var versionCode: Long = 0
        private set
        get() {
            if (field == 0L) fillVersionFields()
            return field
        }

    var installTime: Long = 0
        private set
        get() {
            if (field == 0L) fillVersionFields()
            return field
        }

    var updatedTime: Long = 0
        private set
        get() {
            if (field == 0L) fillVersionFields()
            return field
        }

    private fun fillVersionFields() {
        val pi = INSTANCE.packageManager.getPackageInfo(INSTANCE.packageName, 0)
        packageName = pi.packageName
        versionName = pi.versionName ?: ""
        versionCode = PackageInfoCompat.getLongVersionCode(pi)
        installTime = pi.firstInstallTime
        updatedTime = pi.lastUpdateTime
    }
}
